package com.gomore.opple.module.addressdialog;

import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.web.cgform.resellerstore.entity.ToStoreAddress;

import java.util.Date;

import javax.inject.Inject;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class AddressDialogPresenter implements AddressDialogContract.Presenter {

    private DataRepository mDataRepositroy;
    private final AddressDialogContract.View mView;
    private CompositeSubscription mSubscriptions;

    @Inject
    AddressDialogPresenter(DataRepository dataRepository, AddressDialogContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }

    /**
     * 初始化数据
     */
    @Override
    public void prepareInitData() {

    }

    @Override
    public void saveStoreAddress(String stroeCode, String province, String city, String country) {
        ToStoreAddress toStoreAddress = new ToStoreAddress();
        toStoreAddress.setCreateDate(new Date());
        toStoreAddress.setStorecode(stroeCode);
        toStoreAddress.setResellerid(mDataRepositroy.getUser().getEmployee().getCurrentDepart().getId());
        toStoreAddress.setProvince(province);
        toStoreAddress.setCity(city);
        toStoreAddress.setCountry(country);
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.saveStoreAddress(toStoreAddress)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String string) {
                        super.onNext(string);
                        mView.hideProgressDialog();
                        mView.finishActivity();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }
}
